import Vue from "vue";
import store from "./store";
import router from "./router";
import axios from "@/api";

// 格式化时间
Vue.prototype.dateFormat = (time, format = "yyyy/MM/dd hh:mm") => {
  if (isNaN(time)) return "";

  let date = new Date(time * 1000);
  let o = {
    "M+": date.getMonth() + 1, // 月
    "d+": date.getDate(), // 日
    "h+": date.getHours(), // 时
    "m+": date.getMinutes(), // 分
    "s+": date.getSeconds(), // 秒
    "q+": Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds() // 毫秒
  };
  if (/(y+)/.test(format)) {
    format = format.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  for (let k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
    }
  }
  return format;
};

// 屏幕下方悬浮提示
Vue.prototype.toast = (msg, duration) => {
  if (window.timeout) {
    window.clearTimeout(window.timeout);
  }

  msg = msg || "";
  store.commit("SET_TOAST_MSG", { msg });

  duration = duration || 1500;
  window.timeout = window.setTimeout(() => {
    store.commit("SET_TOAST_MSG", { msg: "" });
  }, duration);
};

// 保留指定位数小数，默认2位
Vue.prototype.toFixed = (number, n = 2) => {
  var num = number + "";
  var dotIndex = num.indexOf(".");
  if (dotIndex > -1) {
    num = num.substring(0, dotIndex + n + 1);
  }
  return +num;
};

// 获取 url 参数
Vue.prototype.getUrlParams = key => {
  let search = window.location.search;
  if (!search) return key ? "" : {};

  let res = "";
  if (key) {
    let reg = new RegExp(`${key}=([^&|$]*)`, "g");
    let exec = reg.exec(search);
    res = exec ? exec[1] : "";
  } else {
    res = {};
    let params = search.substr(1).split("&");
    params.map(param => {
      let [key, value] = param.split("=");
      res[key] = value;
    });
  }

  return res;
};

// 加群
Vue.prototype.addGroup = group => {
  if (typeof group === "string") {
    window.open(group);
  } else {
    // let ua = navigator.userAgent
    // if (/ip[hone|ad|od]/i.test(ua)) {
    //   window.open(group.ios_key)
    // } else if (/mobile/i.test(ua)) {
    //   window.open(group.and_key)
    // } else {
    //   window.open(group.idkey)
    // }
    window.open(group.idkey);
  }
};

// 分享
Vue.prototype.shareToFriend = (show = true) => {
  let env = Vue.prototype.huo.getEnvironment();

  if (env.indexOf("h5_app") > -1) {
    store.commit("SET_POP_STATUS", {
      type: "share",
      show
    });
  } else {
    store.commit("SET_POP_STATUS", {
      type: "poster",
      show
    });
  }
};
Vue.prototype.setCookie = (name, value) => {
  var Days = 30;
  var exp = new Date();
  exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
  document.cookie =
    name + "=" + escape(value) + ";expires=" + exp.toGMTString();
};
// 玩游戏
const platGame = (url, ish5, item) => {
  if (window.localStorage.getItem("loginFlag") == 1 && ish5) {
    HuoSdk.login();
    return false;
  }
  if (!url && !ish5) {
    alert("APP暂未上架");
    return;
  }
  let isWechat = /micromessenger/i.test(navigator.userAgent);
  if (isWechat) {
    if (!ish5) {
      store.commit("SET_POP_STATUS", {
        type: "wxGuide",
        show: true
      });
      return false;
    } else {
      window.location.href = url;
      return false;
    }
  }
  if (!url) {
    return false;
  } else {
    function setCookie(name, value) {
      var Days = 30;
      var exp = new Date();
      exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
      document.cookie =
        name + "=" + escape(value) + ";expires=" + exp.toGMTString();
    }
    let ua = navigator.userAgent;
    var isIos = /iPhone|iPad|iPod/.test(ua);
    if (isIos) {
      if (item) {
        console.log(ish5);
        router.push(`/game?id=${item.game_id}`);
        if (ish5) {
          console.log(45645665);
          setCookie("first", 1);
        }
      } else {
        window.location.href = url;
      }
    } else {
      window.location.href = url;
    }
  }
};
Vue.prototype.playGame = platGame;

Vue.prototype.toGameDetail = (id, url, type) => {
  router.push(`/game?id=${id}`);

  // if (type === 5) {
  //   window.location.href = url
  // } else {
  //   router.push(`/game?id=${id}`)
  // }
};

/**
 * @method advertiseGameDownload 广告页下载并上报信息
 * @param {URL} app_url 小氪手游下载地址
 * @param {Object} reportParam 广告下载上报信息 { app_id: 下载游戏ID, click_id: 来源渠道ID, uuid: 模拟设备唯一标识符 }
 */
Vue.prototype.advertiseGameDownload = (app_url, reportParam) => {
  platGame(app_url);
  axios.advertiseClickReport(
    reportParam,
    data => {
      console.log(`返回结果：${data.msg}`);
    },
    err => {
      console.log(`广告点击上报异常：${err}`);
    }
  );
};

// 连通 APP
Vue.prototype.huo = {
  // 获取当前环境
  // http://doc.1tsdk.com/138?page_id=3079
  getEnvironment() {
    let env = "";
    try {
      env = window.huo.getEnvironment();
    } catch (err) {}
    return env;
  },

  // 分享
  // http://doc.1tsdk.com/138?page_id=3098
  share(params) {
    try {
      window.huo.share(JSON.stringify(params));
    } catch (err) {
      window.alert(JSON.stringify(err));
    }
  },

  // 调用第三方登录
  // http://doc.1tsdk.com/138?page_id=3100
  loginByThird(params) {
    try {
      window.huo.loginByThird(JSON.stringify(params));
    } catch (err) {
      window.alert(JSON.stringify(err));
    }
  }
};

// APP 登录回调
window.app_login_callback = res => {
  let data = JSON.parse(res);

  if (data.code !== 2) {
    Vue.prototype.toast("登录失败！");
    return false;
  }

  let state = "";
  try {
    state = window.huo.getAgent();
  } catch (err) {}

  let types = {
    2: "qq",
    3: "weixin",
    4: "weibo"
  };

  store.dispatch("saveOauthInfo", {
    state,
    type: types[data.type],
    openid: data.openid,
    unionid: data.unionid,
    nickname: data.nickname,
    gender: data.gender,
    avatar: data.head_img,
    access_token: data.access_token,
    expires_in: data.expires_date,
    refresh_token: data.refresh_token
  });
};
// APP 分享回调
window.app_share_callback = res => {
  let data = JSON.parse(res);
  if (data.status === 2) {
    Vue.toast("分享成功");
  } else {
    Vue.toast("分享失败");
  }
};

// 取 cookie
window.getCookie = key => {
  let cookie = document.cookie;
  let reg = new RegExp(`${key}=([^;]*)`, "gi");
  let exec = reg.exec(cookie);

  let value = "";
  if (exec) {
    value = exec[1];
  }
  return value;
};

// wx jssdk 支付
window.callWxPay = data => {
  function onBridgeReady() {
    window.WeixinJSBridge.invoke("getBrandWCPayRequest", data, function(res) {
      if (res.err_msg === "get_brand_wcpay_request:ok") {
      }
    });
  }

  if (typeof WeixinJSBridge === "undefined") {
    if (document.addEventListener) {
      document.addEventListener("WeixinJSBridgeReady", onBridgeReady, false);
    } else if (document.attachEvent) {
      document.attachEvent("WeixinJSBridgeReady", onBridgeReady);
      document.attachEvent("onWeixinJSBridgeReady", onBridgeReady);
    }
  } else {
    onBridgeReady();
  }
};

/**
 * @method simulate16 模拟生成16进制数
 */
function simulate16() {
  var randomNum = Math.round(Math.random() * 15);
  var temp;

  switch (randomNum) {
    case 10:
      temp = "a";
      break;
    case 11:
      temp = "b";
      break;
    case 12:
      temp = "c";
      break;
    case 13:
      temp = "d";
      break;
    case 14:
      temp = "e";
      break;
    case 15:
      temp = "f";
      break;
    default:
      temp = String(randomNum);
      break;
  }

  return temp;
}

/**
 * @method buildUUID 生成类似UUID的唯一标识符
 */
export function buildUUID() {
  var map = [8];
  var temp = "";

  for (var i = 0, length = map.length; i < length; i++) {
    var flag = "";
    var j = 0;

    while (j < map[i]) {
      flag += simulate16();
      j++;
    }

    temp += i ? "-" + flag : flag;
  }

  return temp;
}

/**
 * @method getQueryItem 解析URL参数
 * @param {String} url 解析url
 * @param {String} name 解析参数名
 */
export function getQueryItem(url, name) {
  var index = url.indexOf("?");

  if (index > -1) {
    const str = url.slice(index + 1);
    const [temp] = str.split("&").filter(item => item.indexOf(`${name}=`) > -1);
    return temp.slice(name.length + 1);
  } else {
    return null;
  }
}

export function getPlatform() {
  var platform = null;
  var browser = {
    versions: (function() {
      var u = navigator.userAgent,
        app = navigator.appVersion;
      return {
        //移动终端浏览器版本信息
        trident: u.indexOf("Trident") > -1, //IE内核
        presto: u.indexOf("Presto") > -1, //opera内核
        webKit: u.indexOf("AppleWebKit") > -1, //苹果、谷歌内核
        gecko: u.indexOf("Gecko") > -1 && u.indexOf("KHTML") == -1, //火狐内核
        mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
        ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
        android: u.indexOf("Android") > -1 || u.indexOf("Linux") > -1, //android终端或uc浏览器
        iPhone: u.indexOf("iPhone") > -1, //是否为iPhone或者QQHD浏览器
        iPad: u.indexOf("iPad") > -1, //是否iPad
        webApp: u.indexOf("Safari") == -1 //是否web应该程序，没有头部与底部
      };
    })(),
    language: (navigator.browserLanguage || navigator.language).toLowerCase()
  };

  if (browser.versions.mobile) {
    var ua = navigator.userAgent.toLocaleLowerCase();

    if (ua.match(/MicroMessager/i) === "micromessager") {
      platform = "wechat";
    } else if (ua.match(/Weibo/i) === "weibo") {
      platform = "weibo";
    } else if (ua.match(/QQ/i) === "qq") {
      platform = "qq";
    } else if (
      browser.versions.ios ||
      browser.versions.iPad ||
      browser.versions.iPhone
    ) {
      platform = "ios";
    } else {
      platform = "android";
    }
  } else {
    platform = "pc";
  }

  return platform;
}
